﻿using Abp.Domain.Uow;
using Abp.Threading.BackgroundWorkers;
using Abp.Threading.Timers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WorkflowCoreDockingDemo.Workflows
{
    public class SyncWorkStatusBackgroundWorker : PeriodicBackgroundWorkerBase
    {
        private readonly WorkflowAdapter workflowAdapter;
        private readonly IEnumerable<IWorkflowStatusUpdatable> _WorkflowStatusUpdatables;
        public SyncWorkStatusBackgroundWorker(AbpTimer timer, WorkflowAdapter workflowAdapter, IEnumerable<IWorkflowStatusUpdatable> workflowStatusUpdatables) : base(timer)
        {
            Timer.Period = 5000;
            this.workflowAdapter = workflowAdapter;
            _WorkflowStatusUpdatables = workflowStatusUpdatables;
        }
        [UnitOfWork]
        protected override void DoWork()
        {
            foreach (var _WorkflowStatusUpdatable in _WorkflowStatusUpdatables)
            {
                var worktasks =_WorkflowStatusUpdatable.GetUpdatableWorkTasks();
                var entityGroups = worktasks.GroupBy(w => w.entityFullName);
                foreach (var entityGroup in entityGroups)
                {
                    var remoteWorkTasks = workflowAdapter.GetAllProcessingWorkTasksByEntityType(entityGroup.Key, entityGroup.Select(g => g.entityKeyValue.ToString()).ToArray()).Result;
                    if(remoteWorkTasks.Count()>0)
                    {
                        foreach (var remoteWorkTask in remoteWorkTasks)
                        {
                            _WorkflowStatusUpdatable.UpdateWorkflowStatus(remoteWorkTask.EntityFullName, remoteWorkTask.EntityKeyValue, remoteWorkTask.WorkTaskStatus).Wait();
                        }
                    }
                }
            }
        }
    }
}
